import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { login as apiLogin, getCurrentUser } from '@/services/authService'

export const useAuthStore = defineStore('auth', () => {
  const token = ref(localStorage.getItem('token') || '')
  const user = ref(null)

  const isAuthenticated = computed(() => !!token.value)
  const isAdmin = computed(() => user.value?.role === 'admin')

  async function login(username, password) {
    try {
      const response = await apiLogin(username, password)
      token.value = response.access_token
      localStorage.setItem('token', response.access_token)
      
      // Fetch user info after login
      await fetchCurrentUser()
      
      return true
    } catch (error) {
      console.error('Login failed:', error)
      throw error
    }
  }

  async function fetchCurrentUser() {
    try {
      const userData = await getCurrentUser()
      user.value = userData
    } catch (error) {
      console.error('Failed to fetch user:', error)
      logout()
    }
  }

  function logout() {
    token.value = ''
    user.value = null
    localStorage.removeItem('token')
  }

  // Initialize user on store creation
  if (token.value) {
    fetchCurrentUser()
  }

  return {
    token,
    user,
    isAuthenticated,
    isAdmin,
    login,
    logout,
    fetchCurrentUser
  }
})
